//
//  LGTPostUploadImageStepVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/23.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit
import WisdomHUD

class LGTPostUploadImageStepVC: LGTBaseVC, PhotoDelegate{
    var textView:LGTInputTextView?
    var path:IndexPath?
    var type:Int = 0  //0上传验证图  1上传说明图 2上传二维码
    var addImage:UIImageView?
    var index:Int = 0 //在视图上的索引位置
    var clickInfoBlock:ClickInfoBlock? //保存回掉
    var selectImageInfo:Dictionary<String, Any>?
    var selectImage:UIImage?
    private var _info:Dictionary<String, Any>?
    var photoManager:PhotoManager? = {
        let photoManagr1 = PhotoManager()
        return photoManagr1
    }()
    var upload:Bool = false //是否需要上传
    
    //初始化信息
    var info:Dictionary<String, Any>?{
        get{
            return _info
        }set{
            _info = newValue
            self.selectImageInfo = _info?["selectInfo"] as? Dictionary<String, Any>
            self.path = newValue?["path"] as? IndexPath
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    override func setUI() {
        super.setUI()
        self.view.backgroundColor = BlackAlphaColor
        let backView:UIImageView = LGTViewCreateUtil.share.createImageViewCorner(corner: SizeFitFloat(10))
        self.view.addSubview(backView)
        backView.isUserInteractionEnabled = true
        backView.backgroundColor = UIColor.white
        backView.snp.makeConstraints { (make) in
            make.center.equalTo(self.view)
            make.width.equalTo(SizeFit(303))
            make.height.equalTo(SizeFit(437))
        }
    
        let data:Array<Dictionary<String, Any>> = [["title":"上传验证图",
                                                    "subtitle":"验证图*",
                                                    "place1":"适用于需要验证图，引导接单人操作， 输入内容，详细说明需要注意的事项。"],
                                                   ["title":"上传说明图",
                                                    "subtitle":"说明图*",
                                                    "place1":"适用于需要图文说明，引导悬赏人的操作， 输入内容，详细说明需要注意的事项。"],
                                                   [
                                                   "title":"上传二维码",
                                                    "subtitle":"二维码*",
                                                    "place1":"适用于需要扫描二维码的操作，输入内容 详细描述如何扫描二维码。"],
                                                   ]
        
        let info:Dictionary<String, Any> = data[self.type]
        let title:String = info["title"] as! String
        let subtitle:String = info["subtitle"] as! String
        let place1:String = info["place1"] as! String
        
        let titleLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: 0, text: title)
        backView.addSubview(titleLabel)
        
        titleLabel.font = UIFont.boldSystemFont(ofSize: SizeFitFloat(18))
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(backView)
            make.height.equalTo(SizeFit(18))
            make.top.equalTo(SizeFit(22))
        }
        
        let clostBtn = LGTViewCreateUtil.share.createLGTButton(image: "close_icon", selected: "close_icon", dW: SizeFitFloat(10), dH: SizeFitFloat(10))
        backView.addSubview(clostBtn)
        clostBtn.snp.makeConstraints { (make) in
            make.width.height.equalTo(SizeFit(13))
            make.top.equalTo(SizeFit(23))
            make.right.equalTo(-SizeFit(24))
        }
        
        let descLabel:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(15), text: "步骤说明*")
        backView.addSubview(descLabel)
        descLabel.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFit(27))
            make.top.equalTo(SizeFit(59))
            make.height.equalTo(SizeFitFloat(15))
        }
        
        let imageView:UIImageView = LGTViewCreateUtil.share.createImageViewCorner(corner: SizeFitFloat(3))
        imageView.isUserInteractionEnabled = true
        imageView.backgroundColor = ViewBackColor
        backView.addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(backView)
            make.height.equalTo(SizeFitFloat(102))
            make.width.equalTo(SizeFitFloat(252))
            make.top.equalTo(SizeFit(84))
        }
        
        self.textView = LGTViewCreateUtil.share.createInputTextView(placehoder: place1, fontSize: SizeFitFloat(12), limitCout: 200)
        imageView.addSubview(self.textView!)
        self.textView?.textView.backgroundColor = UIColor.clear
        self.textView?.textView.isScrollEnabled = true
        self.textView?.showCount = true
        self.textView?.backgroundColor = UIColor.clear
        self.textView!.snp.makeConstraints({ (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(SizeFit(10))
            make.width.equalTo(SizeFitFloat(230))
            make.bottom.equalTo(SizeFit(-18))
        })
        
        let titleLabel2:UILabel = LGTViewCreateUtil.share.createLabel(textAlignment: NSTextAlignment.left, textColor: TextColor, fontSize: SizeFitFloat(15), text: subtitle)
        backView.addSubview(titleLabel2)
        //titleLabel2.font = UIFont.boldSystemFont(ofSize: SizeFitFloat(18))
        titleLabel2.snp.makeConstraints { (make) in
            make.left.equalTo(SizeFit(27))
            make.height.equalTo(SizeFit(15))
            make.top.equalTo(SizeFit(205))
        }
        
        self.addImage = LGTViewCreateUtil.share.createImageView(image: "addto")
        self.addImage?.layer.masksToBounds = true
        backView.addSubview(self.addImage!)
        self.addImage?.isUserInteractionEnabled = true
        let tap:UITapGestureRecognizer = UITapGestureRecognizer.init(target: self
            , action: #selector(addImageAction))
        self.addImage?.addGestureRecognizer(tap)
        self.addImage!.snp.makeConstraints({ (make) in
            make.left.equalTo(SizeFit(27))
            make.width.height.equalTo(SizeFit(80))
            make.top.equalTo(SizeFit(235))
        })
        
        let sureButton:UIButton = LGTViewCreateUtil.share.createTextLGTButton(title: "确认添加", font: Font_Normal_15, color: UIColor.white, selectedColor: UIColor.white, corner:SizeFitFloat(20), backColor: YellowColor)
        backView.addSubview(sureButton)
        sureButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(SizeFit(40))
            make.width.equalTo(SizeFit(252))
            make.top.equalTo(SizeFit(340))
        }
        
        let cancelBtn:UIButton = LGTViewCreateUtil.share.createTextLGTButton(title: "取消", font: Font_Normal_15, color: YellowColor, selectedColor: YellowColor, corner:SizeFitFloat(20), backColor: UIColor.clear)
        backView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(SizeFit(40))
            make.width.equalTo(SizeFit(252))
            make.top.equalTo(sureButton.snp_bottomMargin).offset(SizeFit(10))
        }
        cancelBtn.addTarget(self, action: #selector(closeAction), for: UIControl.Event.touchUpInside)
        clostBtn.addTarget(self, action: #selector(closeAction), for: UIControl.Event.touchUpInside)
        sureButton.addTarget(self, action: #selector(sureAction), for: UIControl.Event.touchUpInside)
        
        if self.info != nil {
            self.textView?.text = self.info?["stepText"] as? String ?? ""
            let selectInfo:Dictionary<String, Any>? = self.info?["selectInfo"] as! Dictionary<String, Any>
            let url:String = selectInfo?["url"] as? String ?? ""
            self.addImage?.sd_setImage(with: URL.init(string: url), placeholderImage: UIImage.init(named: ""), options: SDWebImageOptions.retryFailed, context: nil)
        }
    }
    
    @objc func addImageAction(){
        print("addImage")
        //都不做裁剪
        self.photoManager?.unNeedCrop = true
        self.photoManager?.delegate = self as PhotoDelegate
        let alertVC = UIAlertController.init(title: "获取方式", message: "", preferredStyle: UIAlertController.Style.actionSheet)
        weak var weakSelf = self
        let playAction = UIAlertAction.init(title: "拍照", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.photoManager?.actionSheet(UIActionSheet(), clickedButtonAt: 0)
        }
        let ablumAction = UIAlertAction.init(title: "从相册中选择", style: UIAlertAction.Style.default) { (action) in
            weakSelf?.photoManager?.actionSheet(UIActionSheet(), clickedButtonAt: 1)
        }
        let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertAction.Style.cancel) { (action) in
            
        }
        alertVC.addAction(playAction)
        alertVC.addAction(ablumAction)
        alertVC.addAction(cancelAction)
        self.present(alertVC, animated: true, completion: nil)
    }
    
    @objc func closeAction(){
        print("closeAction")
        self.dismiss(animated: false, completion: nil)
    }
    
    @objc func sureAction(){
        print("sureAction")
        if self.textView?.textView.text.count == 0{
            WisdomHUD.showText(text: "请输入步骤说明")
            return
        }
        
        //没有选择
        if self.selectImage == nil && self.selectImageInfo == nil{
            ////0上传验证图  1上传说明图 2上传二维码
            let data:Array<String> = ["验证图", "说明图", "二维码"]
            WisdomHUD.showText(text: "请选择\(data[self.type])")
            return
        }
        
        // 图片数据没有改变
        if self.upload == false{
            var info:Dictionary<String, Any?> = ["index": self.index,
                                                 "stepText": self.textView!.textView.text,
                                                 "imageAndText": true,
                                                 "selectInfo":self.selectImageInfo,
                                                 "type": self.type]
            if self.path != nil{
                info["path"] = self.path!
            }
            if self.clickInfoBlock != nil{
                self.clickInfoBlock!(self.index ?? 0, info)
            }
            WisdomHUD.dismiss()
            self.dismiss(animated: false, completion: nil)
            return
        }
        
        let data:Data = self.selectImage?.jpegData(compressionQuality: 0.8) ?? Data()
        let param:Dictionary<String, Any> = ["image":data]
        weak var weakSelf = self
        WisdomHUD.showLoading()
        LGTHttpUtil.httpUtil.uploadData(url: Upload_Image_URL, param: param, success: { (json) in
            
            print("json")
            //步骤添加
            var info:Dictionary<String, Any?> = ["index": weakSelf?.index,
                                                "stepText": weakSelf?.textView!.textView.text,
                                                "imageAndText": true,
                                                "selectInfo":json["data"]]
            if weakSelf?.path != nil{
                info["path"] = weakSelf?.path!
            }
            WisdomHUD.dismiss()
            
            if weakSelf?.clickInfoBlock != nil{
                weakSelf?.clickInfoBlock!(weakSelf?.index ?? 0, info)
            }
            weakSelf?.dismiss(animated: false, completion: nil)
        }) { (json) in
            WisdomHUD.dismiss()
            WisdomHUD.showError(text: json["message"] as? String ?? "")
        }
    }
    
    
    //裁剪图片代理
    func imageCropper(_ cropperViewController: VPImageCropperViewController, didFinished editedImage: UIImage) {
        //       self.upload = true
        //        var editedImageNew:UIImage = editedImage
        //        var imageW:CGFloat = editedImage.size.width
        //        var imageH:CGFloat = editedImage.size.height
        //        var needCrop:Bool = false
        //        //款高不能超过1600
        //        if imageW > imageH && imageW > ImageLimitMax{
        //            let rate = ImageLimitMax / imageW
        //            imageH = rate * imageH
        //            imageW = ImageLimitMax
        //            needCrop = true
        //        }else if imageH > imageW && imageH > ImageLimitMax{
        //            let rate = ImageLimitMax / imageH
        //            imageW = rate * imageW
        //            imageH = ImageLimitMax
        //            needCrop = true
        //        }
        //
        //        if needCrop == true{
        //            editedImageNew = LGTOCBaseUtil.compressOriginalImage(editedImage, to: CGSize.init(width: imageW, height: imageH))
        //        }
        self.upload = true
        self.selectImage = BaseUtil.baseUtil.getUploadImage(editedImage: editedImage)
        self.addImage?.image = self.selectImage
        if cropperViewController != nil{
            cropperViewController.dismiss(animated: true, completion: nil)
        }
    }
    
    func imageCropperDidCancel(_ cropperViewController: VPImageCropperViewController!) {
        cropperViewController.dismiss(animated: true, completion: nil)
    }
    
    func finish(_ controller: UIViewController!) {
        self.present(controller, animated: true, completion: nil)
    }
    
    func getCropSize() -> CGRect {
        return CGRect.init(x: 0, y: (KScreenH - KScreenW)/2, width: KScreenW, height: KScreenW)
    }
    
}
